package com.qf.service.impl.blog;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.api.blog.dto.WikiDTO;
import com.qf.api.blog.entity.WikiEntity;
import com.qf.api.blog.service.WikiService;
import com.qf.api.front.vo.WikiVO;
import com.qf.core.exception.BaseException;
import com.qf.core.response.ResponseCode;
import com.qf.dao.blog.mapper.WikiMapper;
import com.qf.security.utils.SecurityUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author sin
* @description 针对表【t_wiki(知识库表)】的数据库操作Service实现
* @createDate 2025-05-23 14:19:29
*/
@Service
public class WikiServiceImpl extends ServiceImpl<WikiMapper, WikiEntity>
    implements WikiService {

    @Resource
    private WikiMapper wikiMapper;

    /**
     * 新增知识库，如果title已经存在就返回异常（知识库已经存在）
     **/
    @Override
    public boolean addWiki(WikiDTO wikiDTO) {
        // 如果title已经存在就不用新增 这块直接抛出异常就终止了
        checkWikiTitle(wikiDTO.getTitle());
        WikiEntity wikiEntity = BeanUtil.copyProperties(wikiDTO, WikiEntity.class);
        Long author_id = SecurityUtils.getUserInfo().getUser().getId();
        wikiEntity.setAuthorId(author_id);
        return wikiMapper.insert(wikiEntity) > 0;
    }

    @Override
    public boolean editWiki(Long id, WikiDTO wikiDTO) {
        // 先判断是否存在该id对应的知识库
        WikiEntity wikiEntity = wikiMapper.selectById(id);
        if(wikiEntity == null) {
            throw new BaseException(ResponseCode.WIKI_IS_NOT_EXIT);
        }
        wikiEntity = BeanUtil.copyProperties(wikiDTO, WikiEntity.class);
        Long author_id = SecurityUtils.getUserInfo().getUser().getId();
        wikiEntity.setAuthorId(author_id);
        return wikiMapper.updateById(wikiEntity) > 0;
    }

    @Override
    public WikiDTO getArticleById(Long id) {
        WikiEntity wikiEntity = wikiMapper.selectById(id);
        if(wikiEntity == null)
            throw new BaseException(ResponseCode.GET_DATA_ERROR);
        return BeanUtil.copyProperties(wikiEntity,WikiDTO.class);
    }

    @Override
    public boolean updateWikiTopOrPublish(Long id, Integer type, Integer value) {
        int result = -1;
        if (type == 0) {
            result = wikiMapper.updateWikiTop(id, value);
        } else {
            result = wikiMapper.updateWikiPublish(id, value);
        }
        return result > 0;
    }

    @Override
    public List<WikiVO> getWikiPage(String title) {
        return wikiMapper.getWikiPage(title);
    }

    @Override
    public boolean checkWikiTitle(String title) {
        Long count = wikiMapper.selectCount(new QueryWrapper<WikiEntity>().eq("title", title));
        if(count > 0)
            throw new BaseException(ResponseCode.WIKI_IS_EXIT);
        return true;
    }

}




